const db = require('../config/db');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('../config/config');
const { sendError } = require('../utils/response');


module.exports = {
  // 用户注册
  async register(username, email, password, phone, role = 'customer') {
    // 检查用户名和邮箱是否已存在
    const [users] = await db.execute(
      'SELECT id FROM users WHERE username = ? OR email = ?',
      [username, email]
    );
    
    if (users.length > 0) {
      throw new Error('用户名或邮箱已存在');
    }
    
    const hashedPassword = await bcrypt.hash(password, 10);
    const [result] = await db.execute(
      'INSERT INTO users (username, email, password, phone, role) VALUES (?, ?, ?, ?, ?)',
      [username, email, hashedPassword, phone, role]
    );
    return result.insertId;
  },

  // 用户登录
  async login(email, password) {
    const [users] = await db.execute('SELECT * FROM users WHERE email = ?', [email]);
    
    if (users.length === 0) {
      throw new Error('用户不存在');
    }

    const user = users[0];
    const isMatch = await bcrypt.compare(password, user.password);
    
    if (!isMatch) {
      throw new Error('密码错误');
    }


    return {
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        phone: user.phone,
        avatar: user.avatar,
        role: user.role
      },
      token: jwt.sign({ userId: user.id }, config.jwtSecret, { expiresIn: '1h' })
    };
  },

  async loginByPhone(phone, password) {
    const [users] = await db.execute('SELECT * FROM users WHERE phone = ?', [phone]);
    
    if (users.length === 0) {
      throw new Error('用户不存在');
    } 
    const user = users[0];
    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
      throw new Error('密码错误');
    }
    return {
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        phone: user.phone,
        avatar: user.avatar,
        role: user.role
      },
      token: jwt.sign({ userId: user.id }, config.jwtSecret, { expiresIn: '1h' })
    };
  },

  // 用户登录
  async loginUsername(username, password) {
    const [users] = await db.execute('SELECT * FROM users WHERE username = ?', [username]);
    
    if (users.length === 0) {
      throw new Error('用户不存在');
    }

    const user = users[0];
    const isMatch = await bcrypt.compare(password, user.password);
    
    if (!isMatch) {
      throw new Error('密码错误');
    }

    return {
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        phone: user.phone,
        avatar: user.avatar,
        role: user.role
      },
      token: jwt.sign({ userId: user.id }, config.jwtSecret, { expiresIn: '1h' })
    };
  },

  // 获取当前用户信息
  async getCurrentUser(userId) {
    const [users] = await db.execute(
      'SELECT id, username, email, phone, avatar, role FROM users WHERE id = ?',
      [userId]
    );
    
    if (users.length === 0) {
      throw new Error('用户不存在');
    }
    
    return users[0];
  }
};